package com.sevlet;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.util.JsonUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseSevlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String method = req.getParameter("method");
        PrintWriter out = resp.getWriter();
        GsonBuilder gsonBuilder = new GsonBuilder();
        Gson gson = gsonBuilder.create();
        JsonUtil jsonUtil = new JsonUtil();
        if (method==null||method==""){
            jsonUtil.setCode(1);
            jsonUtil.setMsg("未传参method，无法调用方法");
            String s = gson.toJson(jsonUtil);
            out.print(s);
        }else {
            Class<? extends BaseSevlet> aClass = this.getClass();//获取当前调用该方法的类
            try {//HttpServletRequest.class, HttpServletResponse.class
                Method declaredMethod = aClass.getDeclaredMethod(method,HttpServletRequest.class, HttpServletResponse.class);
                Object invoke = declaredMethod.invoke(this, req, resp);//动态调用子类方法
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
                jsonUtil.setCode(1);
                jsonUtil.setMsg("在"+this.getClass().getName()+"中未找到方法名为:"+method+"的方法");
                String s = gson.toJson(jsonUtil);
                out.print(s);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                jsonUtil.setCode(1);
                jsonUtil.setMsg("无法调用"+method+"方法");
                String s = gson.toJson(jsonUtil);
                out.print(s);
            } catch (InvocationTargetException e) {
                e.printStackTrace();
                jsonUtil.setCode(1);
                jsonUtil.setMsg("无法调用"+method+"方法");
                String s = gson.toJson(jsonUtil);
                out.print(s);
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
